/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package health.persistence;

import health.entities.Paciente;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author matheus
 */
public class PacienteDAO {

    Session session = null;

    public PacienteDAO() {
        SessionFactory sessFact = PersistenceUtil.getSessionFactory();
        this.session = sessFact.getCurrentSession();
        
    }

    public void criarOuAtualizarPaciente(Paciente paciente){

        Transaction transaction = null;
        
        transaction = session.beginTransaction();

        session.saveOrUpdate(paciente);

        transaction.commit();
    }

    public Paciente resgatarPaciente(Integer id){
       
        Transaction transaction = null;

        transaction = session.beginTransaction();

        Query query = session.createQuery("from Paciente");

        List result = query.list();
        Iterator it = result.iterator();
        while (it.hasNext()) {
            Paciente p = (Paciente) it.next();
            if (p.getId() == id) {
                return p;
            }
        }

        return null;
    }

    public void updatePacienteToken(String token,Integer id){

        Transaction tr = session.beginTransaction();
        Paciente paciente1 = (Paciente) session.load(Paciente.class, id);
        paciente1.setToken(token);
        tr.commit();

    }

    public void fechaSessao(){
        this.session.close();
    }
}
